﻿using System;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using netCoreStudy.Entities.Base;

namespace netCoreStudy.Attr
{
	public class CustomExceptionAttribute : ExceptionFilterAttribute
	{
		private readonly ILogger<CustomExceptionAttribute> _logger;

		public CustomExceptionAttribute(ILogger<CustomExceptionAttribute> logger)
		{
			_logger = logger;
		}

		/// <summary>
		/// 发生异常后进入这里 
		/// </summary>
		/// <param name="context"></param>
		public override void OnException(ExceptionContext context)
		{
			_logger.LogError("错误捕获");
			if (!context.ExceptionHandled) // 如果异常未被处理 
			{
				context.Result = new OkObjectResult(new ResMsg()
				{
					Code = 500,
					Response = false,
					Msg = context.Exception.Message
				});
			}

			context.ExceptionHandled = true; // 异常被我处理 了
		}
	}
}